var appPath = getAppPath();	

$(function(){
	initJspGrid();// 初始化页面数据
});


// 样版列表初始化
function initJspGrid(){
	
	$('#tmplGrid').datagrid({
	    url:appPath + "/itbScene/getSceneInfoPg.action",
	    height:'full',
	    striped:true,
	    fitColumns:true,
	    queryParams: getQueryParam(),
	    singleSelect:false,
	    // If set to true, clicking a checkbox will always select the row.
	    // If false, selecting a row will not check the checkbox.
	    selectOnCheck:false,
	    // If true, the checkbox is checked/unchecked when the user clicks on a
		// row.
	    // If false, the checkbox is only checked/unchecked when the user clicks
		// exactly on the checkbox.
	    checkOnSelect:true,
	    frozenColumns:[[
	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}
	    ]],
	    columns:[[
			// 微缩图
		    {field:'image',title:'缩略图',width:70,align:'center',sortable:false,
	        	formatter:function(image, rowData, rowIndex){
	        		var retUrl = '';
	        		if (rowData.image) {
	        			retUrl = '<a href="' + rowData.image + '" target="_blank">'
	        				+ '<div style="display:table;text-align:center;height:80px;width:130px;">'
	        				+ '<span align="center" style="display:table-cell;vertical-align:middle">'
	        				+ '<img src="' + rowData.image.replace('oss-cn-hangzhou.aliyuncs.com','img-cn-hangzhou.aliyuncs.com') + '@110h_128w_1l.png'
	        				+ '" style="display:inline;max-height:75px;"></span></div></a>';
	        		}
	        		return retUrl;
	        	}
		    },
    		{field:'edit',title:'编辑',width:25,align:'center',sortable:false,
				formatter:function(value,rowData,rowIndex){
					// if(Number(rowData.publish||'0')==1) return "N/A";
					var ret = "<a href='javascript:void(0)'><img width='12px' height='12px' style='border:0px' src='"+appPath+"/js/lib/jquery-easyui/themes/icons/pencil.png' title='编辑' ";
					ret += " onClick='editTopic("+rowData.s_id+")'/></a>";
					return ret;
				}
			},
	        {field:'s_id',title:'场景ID',width:40,align:'center',sortable:false},
	        {field:'type',title:'场景分类',width:60,align:'center	',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  var tn = '<span style="color:red">暂未定</span>';
		    		  switch(Number(value||'0')){
		    		  	case 1: tn ='场景分类一';break;
		    		  	case 2: tn='场景分类二';break;
		    		  	case 3: tn='场景分类三';break;
		    		  	case 4: tn='场景分类四';break;
		    		  	case 5: tn='场景分类五';break;
		    		  	case 6: tn='场景分类六';break;
		    		  }
		    		  return tn;
		    	  }
	        },
		    {field:'order',title:'排列序号',width:35,align:'center',sortable:false,
			   	  formatter:function(value, rowData, rowIndex){
		    		  if(!rowData.s_id) return "";
		    		  return "<a href='javascript:void(0)' onClick='editNotifyOrder("+rowData.s_id+","+rowData.order+")'>"+rowData.order+"</a>";
		    	  }
		    },
		    {field:'title',title:'标题',width:90,align:'center',sortable:false,},
		    {field:'desc',title:'场景描述内容',width:80,align:'left',sortable:false,
		    	  formatter:function(value, rowData, rowIndex){
		    		  if(!rowData.desc){
		    			  return 'N/A'
		    		  }
		    		  if(rowData.desc&&rowData.desc.length>0){
		    			  	if(rowData.desc.length>10){
		    			  		return rowData.desc.substr(0,9)+'...';			    		
		    			  	}else{
		    			  		return rowData.desc
		    			  	}
		    		  }
		    	  }
		    },
			{field:'url',title:'链接',width:40,align:'center',sortable:false,
				  formatter:function(value, rowData, rowIndex){
					  	if(value){
					  		if(value.indexOf("http")>=0){// 看是否加了带http的头消息
					  		return '<a href="'+rowData.url+'" target="_blank"><span style="color:red;">查看</span></a>'

					  			}	
					  		return '<a href="http://'+rowData.url+'" target="_blank"><span style="color:red;">查看</span></a>'
					  }else{
						  return 'N/A'
					 }
		        }
		    
			},			        
		    {field:'create_time',title:'创建时间',width:55,align:'center',sortable:false,
		    	formatter:function(value, rowData, rowIndex){
		    		var time=new Date(value).format("dd/MM/yyyy hh:mm:ss");
	  		     	return setSpan(time);
	  		  	}
		    },
		    {field:'update_time',title:'修改时间',width:55,align:'center',sortable:false,
		       formatter:function(value, rowData, rowIndex){
		    	   var time=new Date(value).format("dd/MM/yyyy hh:mm:ss");
		    	   return setSpan(time);
	  		  	}
        	}
	    ]],
	    hideColumn:['user_type'],
	    // view: imgView,// 自定义View
	    pagination:true,
		rownumbers:true,
		toolbar:[{
			text:'添加场景',
			iconCls:'icon-add',
			handler:function(){
				addNotify();
			}
		},
		{
			text:'删除场景',
			iconCls:'icon-cancel',
			handler:function(){
				delNotify();
			}
		}
		]	
	});
}

function setSpan(value){
	return '<span style="white-space:pre-wrap;">'+value+'</span>';
}

function editTopic(stId){	
	$("#editTable").show();
	$('#editForm').form('clear');
	$("#topicImg").html('').val('');
	
	$("#trForNew").hide();
	$("#trForEdit").show();
	$("#showTypeForEdit").html('');
	$("#editStId").val(stId);
	var url = appPath + "/itbScene/getOneSceneInfo.action?id="+ stId;//获取一个场景信息
	$.get(url,function(ret){
		if (ret && ret.length>0){
			var info = ret[0];
			var type = Number(info.type||0);
			// var pType = Number(info.parent_type||0);
			// var type = Number(info.type||0);
			
			$("#editTopicTitle").val(info.title||'');
			$("#editTopicDesc").val(info.desc||'');
			$("#editTopicUrl").val(info.url||'');
			$("#editNotifyUse").combobox('select',info.type||'');// 大的分类
			$("#queryDateEndEdit").datebox('setValue',info.end_time||'');
			$("#editCurType").val(type);
			if(type>0) {
				var show = '';
				switch(Number(type)){
					case 1: show = '场景一';break;
					case 2: show = '场景二';break;
					case 3: show = '场景三';break;
					case 4: show = '场景四';break;
					case 5: show = '场景五';break;
					case 6: show = '场景六';break;
				}
	
				$("#showTypeForEdit").html(show);
			}
			
			var showImg = '';
			if(info.image && info.image.length>0) {
				showImg = info.image.replace('oss-cn-hangzhou.aliyuncs.com','img-cn-hangzhou.aliyuncs.com')
					+'@200h_200w_1l.png';
			}
			var imgHtml = '<img src="'+showImg+'" style="display:inline;max-height:100px;max-width:200px">';
			$("#topicImg").append(imgHtml).val(info.image||'');
		}
	});
	
	$("#editBtn").show();
	$('#editDlg').window({
		title:'编辑场景',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	
	cancelPostData();// 上传图片清除 uploader = null
	initOSS();
	$('#editDlg').window('move',{top:20,left:20});
	$('#editDlg').window('open');
}

//添加场景信息
function addNotify(){
	$("#editTable").show();
	$('#editForm').form('clear');
	$("#topicImg").html('').val('');
	$("#trForNew").show();
	$("#trForEdit").hide();
	// $("#editCurType").val(0);
	$("#editTopicType").combobox('select',0);
	$("#editNotifyUse").combobox('select',0).combobox('enable');// 可使用的
	
	$("#editBtn").show();
	$('#editDlg').window({
		title:'新建场景',
		iconCls:'icon-add',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	cancelPostData();// 上传图片清除 uploader = null
	initOSS();
	$('#editDlg').window('move',{top:20,left:20});
	$('#editDlg').window('open');
}

//编辑
function doEdit(){
	var stId = $("#editStId").val();
	var type = $("#editNotifyUse").combobox('getValue');
	var title = $("#editTopicTitle").val()||'';
	var message = $("#editTopicDesc").val()||'';
	var imgUrl = $("#topicImg").val();
	var Url = $("#editTopicUrl").val();
	if(title.length<=0 || message.length<=0){
		return $.messager.alert('提示信息','请填写[场景标题]及[场景描述]!','info');
	}
		var url = appPath+"/itbScene/addSceneInfo.action"
		var sendData = {
			"sceneInfoDto.s_id": stId||"",
			"sceneInfoDto.type": Number(type),
			"sceneInfoDto.title": title || "",
			"sceneInfoDto.desc": message || "",
			"sceneInfoDto.image":imgUrl||"",
			"sceneInfoDto.url":Url||""
		};
	    $.post(url, sendData, function(data){  
			if (data == "ok") { 
				$.messager.alert('提示信息','提交成功','info');
				$('#editDlg').window('close');
				doQuery();
	        } else {
	        	$.messager.alert('提示信息','提交失败','info');
	        }
	    });
}


function delNotify(){
	var selectItem=$("#tmplGrid").datagrid("getChecked");// 获取勾选框
	if(!selectItem || selectItem.length == 0){
		$.messager.alert('提示信息','请选择场景信息！','warning');
		return;
	}
	$.messager.confirm("确认",
		"是否确认[删除]所选场景？<br/><span style='color:red'>*对应的[场景信息]将一并删除!</span>",
		function(r){
	        if (r) { 
				var ids = "";
				$.each(selectItem, function(index, item){
					ids = ids + item.s_id + ",";
				});
				var url = appPath+"/itbScene/deleteSceneInfo.action?ids="+ids;
				$.post(url,function(data){
					if(data=="ok"){
						$.messager.alert('提示信息','删除成功','info');
						doQuery();
					}else{
						$.messager.alert('提示信息','删除失败','info');
					}
				});
	        }
		}
	);
}

/**
 * 显示顺序
 */
function editNotifyOrder(s_id,order){
	$("#notifyId").val(s_id);
	$("#notify").val(order);
	
	$("#notifyBtn").show();
	$('#notifyDlg').window({
		title:'显示顺序设定',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#notifyDlg').window('move',{top:20,left:20});
	$('#notifyDlg').window('open');
}

/**
 * 修改显示顺序
 */
function doUpdNotify(){
	var id = $("#notifyId").val();
	var number = $("#notify").val();
	if(!number || number.length == 0 || Number(number)>999 || Number(number)<=0){
		$.messager.alert('提示信息','有效数值范围为：1～999','warning');
		return;
	}
	
	var url = appPath+"/itbScene/updateSceneOrder.action?orderid="+id+"&order="+number;
	$.post(url,function(data){
		if(data=="ok"){
			$.messager.alert('提示信息','显示顺序已更新！','info',function(){
				doQuery();
				$('#notifyDlg').window('close');
			});
		}else {
			$.messager.alert('提示信息','显示顺序更新失败！','warning');
		}
	});
}
/**
 * 结束显示顺序编辑
 */
function cancelUpdNotify(){
	$('#notifyDlg').window('close');
}

function cancelEdit(){
	$('#editDlg').window('close');
}

// 查询参数条件
function getQueryParam(){
	var queryObject = {};
	var findType= $("#editSceneType").combobox('getValue');// 获取场景类型值
	var findTitleName=$("#queryTitleName").val().trim();// 获取场景标题名字
	if(findType && Number(findType||'0')>0) queryObject.findSceneType = findType;// 类型
	if(findTitleName&&findTitleName.length>0) queryObject.findTitleName = findTitleName;// 样版名称
	return queryObject;
}

/**
 * 查询数据
 */
function doQuery(){
	$("#tmplGrid").datagrid('unselectAll');
	$("#tmplGrid").datagrid('load',getQueryParam());
}

//******************************** 上传图片 *******************************
var myDomain = 'http://7xogoq.com1.z0.glb.clouddn.com';
var ossDmain = "http://itbour-back.oss-cn-hangzhou.aliyuncs.com/";
var validFile = false;
var uploader = null;

// 图像缩放
function DrawImage(ImgD,FitWidth,FitHeight){
    var image=new Image();
    image.src=ImgD.src;
    if(image.width>0 && image.height>0){
        if(image.width/image.height>= FitWidth/FitHeight){
            if(image.width>FitWidth){
                ImgD.width=FitWidth;
                ImgD.height=(image.height*FitWidth)/image.width;
            }else{
                ImgD.width=image.width; 
               ImgD.height=image.height;
            }
        } else{
            if(image.height>FitHeight){
                ImgD.height=FitHeight;
                ImgD.width=(image.width*FitHeight)/image.height;
            }else{
                ImgD.width=image.width; 
               ImgD.height=image.height;
            } 
       }
    }
}

function isImage(url) {
    var res, suffix = "";
    var imageSuffixes = ["png", "jpg", "jpeg", "gif", "bmp"];
    var suffixMatch = /\.([a-zA-Z0-9]+)(\?|\@|$)/;

    if (!url || !suffixMatch.test(url)) {
        return false;
    }
    res = suffixMatch.exec(url);
    suffix = res[1].toLowerCase();
    for (var i = 0, l = imageSuffixes.length; i < l; i++) {
        if (suffix === imageSuffixes[i]) {
            return true;
        }
    }
    return false;
}

function doPostData(){// 开始上传
	if (validFile && uploader) {
		uploader.start();
	} else {
		setMsg("red", "请选择图像文件！");
	}
}

function cancelPostData(){ // 取消上传
	if (uploader) {
		uploader.destroy();
		uploader = null;
	}
}

function setMsg(color, msg) {
	$.messager.alert('提示信息',msg,'info');
}

function fmtCreateTime(value, rowData, rowIndex){
	if(!value)return "";
	var s = new Date(value);
	return rowData.create_time=$.DateUtil.format(s,'yyyy/MM/dd hh:mm:ss');
}

function fmtHotFlag(value, rowData, rowIndex){
	if(rowData.hotFlag==1)return "是";
	return "否";
}





// ############### FOR OSS UPLOAD START ###############
//var accessid= '';
//var accesskey= '';
//var uploadHost = 'http://itbour-back.oss-cn-hangzhou.aliyuncs.com';
var g_object_name = '';
var dtNow = Date.parse(new Date()); //Date.parse(new Date())/1000;
//var policyText = {
//"expiration": "2020-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
//"conditions": [
//  ["content-length-range", 0, 104857600] // 设置上传文件的大小限制
//]
//};
//var policyJsonStr = JSON.stringify(policyText);
//var policyBase64 = Base64.encode(policyJsonStr);
//var message = policyBase64;
//var bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, { asBytes: true });
//var signature = Crypto.util.bytesToBase64(bytes);

var OSS_PARAM = {
	expire: 0,
	uploadHost: '',
	accessKeyId: '',
	policyBase64: '',
	signature: '',
	flg: false
};

function randomString(len) {
	len = len || 20;
	var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';   
	var maxLen = chars.length;
	var str = '';
	for (var i = 0; i < len; i++) {
		str += chars.charAt(Math.floor(Math.random() * maxLen));
    }
	return str;
}

function getSuffix(filename) {
    var pos = filename.lastIndexOf('.');
    var suffix = '';
    if (pos != -1) {
        suffix = filename.substring(pos);
    }
    return suffix;
}

function calculate_object_name(filename) {
	if (g_object_name){
		g_object_name = '';
	}
	var now = new Date(); 
	var nowStr = now.format("yyyy/MM/dd/hhmmssS_");
    g_object_name = "image/U"+g_userId+"/"+nowStr + randomString(20);
}

function set_upload_param(up, filename, ret) {
	// 判断当前expire是否超过了当前时间,如果超过了则重新取
	dtNow = Date.parse(new Date());//  Date.parse(new Date())/1000
	OSS_PARAM.flg = false;
    if (OSS_PARAM.expire < dtNow + 5000) {// 5s
    	var url = appPath+"/itbImg/getOSSToken.action";
        $.get(url, function(data){  
    		if (data && data.signature) { 
    			OSS_PARAM.expire = data.expire;
    			OSS_PARAM.uploadHost = data.uploadHost;
    			OSS_PARAM.accessKeyId = data.accessKeyId;
    			OSS_PARAM.policyBase64 = data.policyBase64;
    			OSS_PARAM.signature = data.signature;
    			OSS_PARAM.flg = true;
    			
    			doUpStart(up, filename, ret);
            } else {
            	$.messager.alert('提示信息','上传异常, 请重新尝试!','info');
            }  
        });
    } else {
    	doUpStart(up, filename, ret);
    }
}

function doUpStart(up, filename, ret){
	if (filename && filename != '') {
        calculate_object_name(filename);
    }
    var new_multipart_params = {
        'key' : g_object_name,
        'policy': OSS_PARAM.policyBase64,
        'OSSAccessKeyId': OSS_PARAM.accessKeyId, 
        'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
        'signature': OSS_PARAM.signature,
    };

    up.setOption({
        'url': OSS_PARAM.uploadHost,
        'multipart_params': new_multipart_params
    });

    up.start();
}

function clearUploadList() {
	$("#topicImg").html('');
	$("#topicImg").val('');
}

function initOSS() {
	if (uploader) {
		uploader.destroy();
		uploader = null;
	}

	uploader = new plupload.Uploader({
		runtimes : 'html5,flash,silverlight,html4',
		browse_button : 'selImgFile', 
	    //multi_selection: false,
		//container: document.getElementById('container'),
		//flash_swf_url : 'lib/plupload-2.1.2/js/Moxie.swf',
		//silverlight_xap_url : 'lib/plupload-2.1.2/js/Moxie.xap',
	    url : 'http://oss.aliyuncs.com',
		init: {
			PostInit: function() {// 当Init事件发生后触发
//				document.getElementById('upImgFile').onclick = function() {
//		            set_upload_param(uploader, '', false);
//		            return false;
//				};
			},

			FilesAdded: function(up, files) {
				clearUploadList();
				$('#uploadMsg').hide();
				
				var delLen = (up.files.length>=files.length)?(up.files.length-files.length):up.files.length;
				up.splice(0,delLen);
				
				var bAllOk = true;
				plupload.each(files, function(file) {
					if (isImage(file.name)) {
						// add file info list
						set_upload_param(uploader, '', false);
				        return false;
					} else {
						bAllOk = false;
						var ngFile = up.getFile(file.id);
						if (ngFile) {
							up.removeFile(ngFile);
						}
					}
				});
				
				if (!bAllOk) {
					setMsg("red", "已过滤非图像文件！");
				}     
			},

			BeforeUpload: function(up, file) {
	            set_upload_param(up, file.name, true);
	        },

			UploadProgress: function(up, file) {
//				var d = document.getElementById(file.id);
//				d.getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
//	            var prog = d.getElementsByTagName('div')[0];
//				var progBar = prog.getElementsByTagName('div')[0];
//				progBar.style.width= 2*file.percent+'px';
//				progBar.setAttribute('aria-valuenow', file.percent);
//				setMsg("green", file.name + ' 上传中...');
			},

			FileUploaded: function(up, file, info) {
	            if (info.status == 200) {
	            	console.log(g_object_name);
	            	var showImg = '';
	            	var tmp = ossDmain+g_object_name
	    			if(g_object_name && g_object_name.length>0) {
	    				showImg = tmp.replace('oss-cn-hangzhou.aliyuncs.com','img-cn-hangzhou.aliyuncs.com')
	    					+'@200h_200w_1l.png';
	    			}
	    			var imgHtml = '<img src="'+showImg+'" style="display:inline;max-height:100px;max-width:200px">';
	    			$("#topicImg").append(imgHtml).val(tmp||'');
	    			
	            } else {
	            	setMsg("red", '上传出错！');
	            }
			},

			Error: function(up, err) {
//				document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.response));
				setMsg("red", err.response);
			}
		}
	});
	
	uploader.init();
}
//############### FOR OSS UPLOAD END ###############

